using System;
using System.Reflection;
using System.ComponentModel;
using System.Collections.Generic;

namespace DotNetCRM.Core.ExtensionMethods
{
    public static class ObjectExtensions
    {
        /// <summary>
        /// Checks parameter for null and throws <code>ArgumentNullException</code> if null.
        /// </summary>
        /// <param name="parm">the parameter to check for null</param>
        /// <exception cref="ArgumentNullException">parm is null</exception>
        public static void CheckNull(this object parm)
        {
            parm.CheckNull(null);
        }

        /// <summary>
        /// Checks parameter for null and throws <code>ArgumentNullException</code> if null.
        /// </summary>
        /// <param name="parm">the parameter to check for null</param>
        /// <param name="parmName">the _name of the parameter</param>
        /// <exception cref="ArgumentNullException">parm is null</exception>
        public static void CheckNull(this object parm, string parmName)
        {
            if (parm == null)
            {
                throw new ArgumentNullException(parmName);
            }
        }

        /// <summary>
        /// Gets the description.
        /// </summary>
        /// <param name="enumeration">The enumeration.</param>
        /// <returns></returns>
        public static string GetDescription(this Enum enumeration)
        {
            FieldInfo fi = enumeration.GetType().GetField(enumeration.ToString());
            DescriptionAttribute[] attributes =
                (DescriptionAttribute[]) fi.GetCustomAttributes(
                                             typeof(DescriptionAttribute), false);
            return (attributes.Length > 0) ? attributes[0].Description : enumeration.ToString();
        }

        public static List<KeyValuePair<Enum, string>> GetEnumList(this Type enumerationType)
        {
            if (enumerationType == null)
            {
                throw new ArgumentNullException("enumerationType");
            }

            //ArrayList list = new ArrayList();
            List<KeyValuePair<Enum, string>> list = new List<KeyValuePair<Enum, string>>();

            Array enumValues = Enum.GetValues(enumerationType);

            foreach (Enum value in enumValues)
            {
                list.Add(new KeyValuePair<Enum, string>(value, GetDescription(value)));
            }
            return list;
        }
    }
}